package com.greate.community.controller;

import com.greate.community.entity.WangEditor;
import com.greate.community.util.JsonResult;
import com.greate.community.util.UploadFileUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("upload")
@RequiredArgsConstructor
public class QiNiuFileController {

    private static final Logger logger = LoggerFactory.getLogger(QiNiuFileController.class);

    private final UploadFileUtil uploadFileUtil;

    @RequestMapping("/files")
    public JsonResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file == null) {
            return JsonResult.error("文件不能为空！");
        }
        String data = uploadFileUtil.saveFile(file);
        if (StringUtils.isNotEmpty(data)) {
            return JsonResult.ok().put("src", data);
        }
        return JsonResult.error("文件上传错误！");
    }

    @RequestMapping("/files/editor")
    public WangEditor uploadFileEditor(@RequestParam("file") MultipartFile file) {
        try {
            String data = uploadFileUtil.saveFile(file);
            if (StringUtils.isEmpty(data)) {
                return new WangEditor(1, null);
            }
            String[] strs = {data};
            return new WangEditor(0, strs);
        } catch (IOException e) {
            logger.error("上传文件失败", e);
        }
        return null;

    }
}
